import { defineComponent, reactive, watch, nextTick } from "vue";
import styles from "./menuSearch.module.less";
import { SearchOutlined } from "@ant-design/icons-vue";
import useNavigator from "@/hooks/useNavigator";
import _ from "lodash";
export default defineComponent({
  props: {
    menuSearchVisible: {
      type: Boolean,
      default: false,
    }
  },
  emits: ['update:menuSearchVisible'],
  setup(props: any, { emit }) {
    const state = reactive({
      // 显示的菜单(关键字过滤)
      list: [],
      // 关键字(页面名或页面路由)
      keyword: '',
    } as {
      list: any[],
      keyword: string,
    })
    const navigator = useNavigator();
    // 源数据(所有有权限的菜单项扁平化处理)
    const origins: any[] = [];
    // 菜单列表
    const menu_list = navigator?.options?.routes?.find(x => x.name === 'index')?.children ?? [];
    // 递归遍历菜单列表
    const treeEach = (arr: any[], baseUrl: string) => {
      arr.forEach(x => {
        x.fullPath = baseUrl + x.path;
        // 不隐藏且有权限的菜单项放入源数据
        !x.meta.hidden && (!x.children || x.children.length === 0) && origins.push(x);
        // 有子菜单项递归处理
        x.children && x.children.length > 0 && treeEach(x.children, baseUrl + x.path + '/');
      })
    }
    treeEach(menu_list, '/');
    // 过滤菜单
    const filterMenu = _.debounce((str: string) => {
      state.list = origins.filter(x => x.meta.title.indexOf(str) > -1 || x.fullPath.indexOf(str) > -1);
    }, 300, { leading: false, trailing: true })
    // 监听关键字,过滤菜单项
    watch(() => state.keyword, (nv, ov) => {
      filterMenu(nv);
    }, {
      immediate: true,
      deep: true,
    })
    // 搜索项点击跳转
    const itemClickHandler = (item: any) => {
      navigator.push({ name: item.name });
      emit('update:menuSearchVisible', false);
    }
    // 监听弹窗打开状态，打开时聚焦输入框
    watch(() => props.menuSearchVisible, (nv, ov) => {
      nextTick(() => {
        if (nv) {
          document.getElementById('menuSearchInput')?.focus();
        }
      })
    }, {
      immediate: true,
      deep: true,
    })
    // 菜单搜索
    const menuSearch = () => (
      <div class={styles.container}>
        <a-input
          id="menuSearchInput"
          v-slots={{
            prefix: () => (
              <SearchOutlined class={styles.icon} />
            )
          }}
          placeholder="菜单搜索：支持中文、路由路径"
          v-model={[state.keyword, 'value']}
        >
        </a-input>
        {
          state?.list?.length > 0 && <div class={styles.listBox}>
            <div class={styles.list}>
              {
                state.list.map(x => (
                  <div class={styles.item} onClick={() => { itemClickHandler(x) }}>{x.meta.title}</div>
                ))
              }
            </div>
          </div>
        }
      </div>
    )
    return {
      menuSearch,
    };
  },
  render() {
    return (
      <this.menuSearch></this.menuSearch>
    )
  }
})